# 导入json模块，用于json数据序列化和反序列化
import json
import os
import requests
import quart
import quart_cors
from quart import request

app = quart_cors.cors(quart.Quart(__name__), allow_origin="https://chat.openai.com")

WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")

WEATHER_API_URL = "https://restapi.amap.com/v3"


def get_citycode(city):
    url = f"{WEATHER_API_URL}/geocode/geo"
    params = {
        "city": city,
        "key": WEATHER_API_KEY,
        "address": city
    }

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()
        data = response.json()
        if data["status"] == "1" and data["geocodes"]:
            citycode = data["geocodes"][0]["adcode"]
            return citycode
        return None
    except requests.exceptions.RequestException as e:
        print(f"Error occurred during GET request: {e}")
        return None


def get_current_weather(city):
    citycode = get_citycode(city)
    if not citycode:
        return None

    url = f"{WEATHER_API_URL}/weather/weatherInfo"
    params = {
        "key": WEATHER_API_KEY,
        "city": citycode
    }

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()
        data = response.json()
        if data["status"] == "1" and data["lives"]:
            weather_info = data["lives"][0]
            weather_info = f"今天{weather_info['province']}{weather_info['city']}的天气{weather_info['weather']},气温{weather_info['temperature']}度,湿度{weather_info['humidity']}%,风速{weather_info['windpower']}级,风向{weather_info['winddirection']},空气质量{weather_info['quality']}"
            return weather_info
        return None
    except requests.exceptions.RequestException as e:
        print(f"Error occurred during GET request: {e}")
        return None


def get_n_day_weather_forecast(city,num_days):
    if num_days > 3 or num_days < 0:
        return "最多查询未来3天的天气预报"

    citycode = get_citycode(city)
    if not citycode:
        return None

    url = f"{WEATHER_API_URL}/weather/weatherInfo"
    params = {
        "key": WEATHER_API_KEY,
        "city": citycode,
        "extensions": "all",
        "output": "JSON"
    }

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()
        data = response.json()
        if data["status"] == "1" and data["forecasts"]:
            forecast_info = data["forecasts"][0]["casts"][num_days]
            weather = f"{forecast_info['date']}，白天天气{forecast_info['dayweather']}，气温{forecast_info['daytemp']}度，风向{forecast_info['daywind']}，风速{forecast_info['daypower']}级；夜间天气{forecast_info['nightweather']}，气温{forecast_info['nighttemp']}度，风向{forecast_info['nightwind']}，风速{forecast_info['nightpower']}级。"
            return weather
        return None
    except requests.exceptions.RequestException as e:
        print(f"Error occurred during GET request: {e}")
        return None

@app.post("/weather/current")
async def get_current_weather():
    city = request.args.get("city")
    response = get_current_weather(city)

    return quart.Response(
        response=json.dumps({"response": response}),
        status=200,
        mimetype="application/json")

@app.post("/weather/forecast")
async def get_n_day_weather_forecast():
    # 从请求参数中获取城市名和预报天数
    city = request.args.get("city")
    num_days = int(request.args.get("num_days"))

    response = get_n_day_weather_forecast(city, num_days)
    # 创建并返回一个 Quart 响应对象，状态码为 200，响应体为 response 的 json 形式
    return quart.Response(json.dumps(response), status=200)


# 定义一个路由处理器，处理 GET 请求，路由为 "/logo.png"
@app.get("/logo.png")
async def plugin_logo():
    # 文件名为 'weather-forecast.png'
    filename = 'weather-forecast.png'
    # 使用 quart.send_file 方法发送文件，并指定 MIME 类型为 'image/png'
    return await quart.send_file(filename, mimetype='image/png')

# 定义一个路由处理器，处理 GET 请求，路由为 "/.well-known/ai-plugin.json"
@app.get("/.well-known/ai-plugin.json")
async def plugin_manifest():
    # 从请求头中获取主机名
    host = request.headers['Host']
    # 打开并读取 ai-plugin.json 文件
    with open("./.well-known/ai-plugin.json") as f:
        text = f.read()
    # 返回一个 Quart 响应对象，响应体为 text，MIME 类型为 "text/json"
    return quart.Response(text, mimetype="text/json")

# 定义一个路由处理器，处理 GET 请求，路由为 "/openapi.yaml"
@app.get("/openapi.yaml")
async def openapi_spec():
    # 从请求头中获取主机名
    host = request.headers['Host']
    # 打开并读取 openapi.yaml 文件
    with open("openapi.yaml") as f:
        text = f.read()
    # 返回一个 Quart 响应对象，响应体为 text，MIME 类型为 "text/yaml"
    return quart.Response(text, mimetype="text/yaml")

# 定义 main 函数，运行 Quart 应用
def main():
    # 启动 Quart 服务器，开启 debug 模式，监听所有 IP 地址，端口为 5001
    app.run(debug=True, host="0.0.0.0", port=5003)


def test():
    city = "上海"
    num_days = 2
    weather_info = get_current_weather(city)
    print(weather_info)

    weather_forecast = get_n_day_weather_forecast(city, num_days)
    print(weather_forecast)

# 如果该文件是直接运行的，而不是作为模块导入的，则调用 main 函数
if __name__ == "__main__":
    test()
    main()